﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Diagnostics;
using RelationTextBox;


////  11.11.2008 adaugare proprietate pentru setari grid
///              initializarea inaltiimi liniilor din grid pe 20
///   12.11.2008 comutator pentru functiunea de selectie a gridului   
///              adaugare randului selectat
///              --gridul functioneaza doar cu selectie unica----
///   17.11.2008 la functia selectie, daca este dialog modal il inchide 
///              automat
///              InitializeBindingSource() - initializeaza binding source pentru
///              gridul principal daca constructorul nu primeste parametru binding source!
namespace ERPStudio
{
    public partial class FrmRezumat : StudioForm
    {

        public event BeforeDelHandlerAfterMessage HandleBeforeDelAfterMessage;
        /// <summary>
        /// Comutator pentru functiunea de selectie a machetei
        /// </summary>
        [Browsable(true)]
        [Description("Daca macheta are si functiunea de selectie")]
        [DefaultValue(false)]
        public Boolean SelectionAddOn
        {
            get
            {
                return _selectionAddOn;
            }
            set
            {
                _selectionAddOn = value;
            }
        }
        private Boolean _selectionAddOn = false;

        private String withSelection = String.Empty;
        public SqlDataReader FormPropReader = null;
        /// <summary>
        /// contine valoare selectata de pe randul curent
        /// </summary>
        public String valoareSelectata = null;
        #region Functii butoane
        /// <summary>
        /// event pentru AddNew la Bindings
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public void Adauga(object sender, EventArgs args)
        {
            if (!this._AllowAddRow)
                return;
            if (ReadOnly)
            {
                MessageBox.Show("Macheta este deschisa doar in consultare!", 
                    "Eroare", 
                    MessageBoxButtons.OK, 
                    MessageBoxIcon.Error);
                return;
            }
            if (!SalvareLocal())
                return;
            try
            {
                Trace.Assert(listBndSourceMain.Count > 0, "Nu s-a completata BindingSource!");
                Trace.Assert(gridRezumat.Count > 0, "Nu s-a setat gridul rezumat");
                

                Int16 indBGV = GetCurrentGrid();
                Trace.Assert(indBGV != -1, "Atentie grid curent inexistent!!!");
                /// daca nu se permite adaugarea de randuri daca nu este setata pentru grid...
                ((BindingSource)gridRezumat[indBGV].DataSource).AddNew();
                int CurrentCell = 0;
                while ((gridRezumat[indBGV][CurrentCell, gridRezumat[indBGV].RowCount-1].ReadOnly ||
                    gridRezumat[indBGV][CurrentCell, gridRezumat[indBGV].RowCount-1].Frozen ||
                    !gridRezumat[indBGV][CurrentCell, gridRezumat[indBGV].RowCount - 1].Visible) && (CurrentCell < gridRezumat[indBGV].ColumnCount))
                    CurrentCell++;

                gridRezumat[indBGV][CurrentCell, gridRezumat[indBGV].RowCount-1].Selected = true;
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
            }
            /// daca a fost definit handlerul afterAdd se va apela
            /// 
            DupaAdauga(0);
        }
        
        /// <summary>
        /// Functia apelata la apasarea butonului de salvare
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// 
        override public void Salvare(object sender, EventArgs args)
        {
            if (ReadOnly)
            {
                return;
            }

            EroareSalvare = false;
            Application.DoEvents();
            try
            {
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
                EroareSalvare = true;
            }


            int idxCurent = -1;
            Trace.Assert(this.listTableAdaptor.Count != 0,"Lista listTableAdaptor nu a fost incarcata cu tabele!!");
            Trace.Assert(listBndSourceMain.Count > 0, "Nu s-a completata BindingSource!");


            Int16 indBGV = GetCurrentGrid();
            if (indBGV != -1)
            {
                foreach (BindingSource bs in listBndSourceMain)
                    if (((BindingSource)gridRezumat[indBGV].DataSource) == bs)
                    {
                        idxCurent = listBndSourceMain.IndexOf(bs);
                        break;
                    }
                Trace.Assert(idxCurent != -1, "Nu exista corespondenta intre grid si date");
            }
            else
                idxCurent = 0;


            int cate = 0;
            try
            {
                ///daca nu sunt validate datele nu se salveaza
                if (!Validate())
                {
                    EroareSalvare = true;
                    return;
                }
                ///EndEdit pt. toate cu exceptia celui curent care se face la sfarsit
                foreach (BindingSource bs in listBndSourceMain)
                    if (bs != listBndSourceMain[idxCurent])
                        bs.EndEdit();
                listBndSourceMain[idxCurent].EndEdit();

                ///init all adapter... cu cel curent la sfarsit
                SqlConnection con = DeschideConexiune(workConnString);
                foreach (SqlDataAdapter ta in listTableAdaptor)
                    if (listTableAdaptor[idxCurent] != ta)
                        InitAdapter(ta, con, null);
                InitAdapter(listTableAdaptor[idxCurent],con,null);
                ///face update la toate
                foreach (SqlDataAdapter ta in listTableAdaptor)
                    if (listTableAdaptor[idxCurent] != ta)
                    {
                        cate += ta.Update(GetDataTable(listTableAdaptor.IndexOf(ta)));
                        
                    }
                cate += listTableAdaptor[idxCurent].Update(GetDataTable(idxCurent));


                if (_DispalySaveStatus)
                {
                    if (cate != 0)
                        SetStatus("S-au salvat " + cate.ToString() + " inregistrari la: " + DateTime.Now.ToString());
                    else
                        SetStatus("");
                   
                }
                
                NoRecUpdated = cate;
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
                EroareSalvare = true;
            }
            finally
            {
                if (listTableAdaptor.Count!=0 && listTableAdaptor[idxCurent].SelectCommand != null)
                    InchideConexiune(listTableAdaptor[idxCurent].SelectCommand.Connection);
            }
        }

        virtual public void Selectie(object sender, EventArgs args)
        {
            selectedRow = null; 
            if(gridRezumat.Count == 0)
                throw(new NotSupportedException("Nu a fost setat gridul rezumat"));
            Int16 indDGV = GetCurrentGrid();
            Trace.Assert(indDGV != -1, "Nu s-au setat gridurile!!");
            if(!ReadOnly)
                Salvare(sender, args);
            if (this.gridRezumat[indDGV].CurrentRow==null || this.gridRezumat[indDGV].CurrentRow.IsNewRow)
            {
                this.DialogResult = DialogResult.None;
                MessageBox.Show("Va rugam selectati un rand existent in baza de date!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (this.gridRezumat[indDGV]!=null)
                selectedRow = this.gridRezumat[indDGV].CurrentRow;
            if (selectedRow!=null)
                selectedDataRow = selectedRow.DataBoundItem as DataRowView;
            this.DialogResult = DialogResult.OK;
            /// daca nu e modal inchide macheta
            if (!this.Modal)
                this.Close();

        }


        public void Primul(object sender, EventArgs args)
        {
            Trace.Assert(listBndSourceMain.Count > 0, "Nu s-a completata BindingSource!");
            Trace.Assert(gridRezumat.Count > 0, "Nu s-a setat gridul rezumat");

            Int16 indBGV = GetCurrentGrid();
            Trace.Assert(indBGV != -1, "Atentie grid curent inexistent!!!");
            ((BindingSource)gridRezumat[indBGV].DataSource).MoveFirst();
        }

        virtual public void Urmator(object sender, EventArgs args)
        {
            Trace.Assert(listBndSourceMain.Count > 0, "Nu s-a completata BindingSource!");
            Trace.Assert(gridRezumat.Count > 0, "Nu s-a setat gridul rezumat");

            Int16 indBGV = GetCurrentGrid();
            Trace.Assert(indBGV != -1, "Atentie grid curent inexistent!!!");
            ((BindingSource)gridRezumat[indBGV].DataSource).MoveNext();
        }
        virtual public void Anterior(object sender, EventArgs args)
        {
            Trace.Assert(listBndSourceMain.Count > 0, "Nu s-a completata BindingSource!");
            Trace.Assert(gridRezumat.Count > 0, "Nu s-a setat gridul rezumat");

            Int16 indBGV = GetCurrentGrid();
            Trace.Assert(indBGV != -1, "Atentie grid curent inexistent!!!");
            ((BindingSource)gridRezumat[indBGV].DataSource).MovePrevious();
        }
        public void Ultimul(object sender, EventArgs args)
        {
            Trace.Assert(listBndSourceMain.Count > 0, "Nu s-a completata BindingSource!");
            Trace.Assert(gridRezumat.Count > 0, "Nu s-a setat gridul rezumat");

            Int16 indBGV = GetCurrentGrid();
            Trace.Assert(indBGV != -1, "Atentie grid curent inexistent!!!");
            ((BindingSource)gridRezumat[indBGV].DataSource).MoveLast();
            UpdateBounds();
        }

        virtual public void Sterge(object sender, EventArgs args)
        {
            if (ReadOnly)
            {
                MessageBox.Show("Macheta este deschisa doar in consultare!",
                    "Eroare",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }

            Trace.Assert(listBndSourceMain.Count > 0, "Nu s-a completata BindingSource!");
            Trace.Assert(gridRezumat.Count > 0, "Nu s-a setat gridul rezumat");

            Int16 indBGV = GetCurrentGrid();
            Trace.Assert(indBGV != -1, "Atentie grid curent inexistent!!!");
            if (!gridRezumat[indBGV].AllowUserToDeleteRows)
                return;
            if (((BindingSource)gridRezumat[indBGV].DataSource).Count == 0)
                return;

            Boolean dacaStergeTmp = true;
            BeforeDelHandlerAfterMessage tempbTmp = HandleBeforeDelAfterMessage;
            if (tempbTmp != null)
                dacaStergeTmp = tempbTmp(this, null,false);

            if (dacaStergeTmp)
            {
                ((BindingSource)gridRezumat[indBGV].DataSource).RemoveCurrent();
                Update();
            }
        }
        public void Card(object sender, EventArgs args)
        {
        }
        #endregion

        public FrmRezumat(ModuleClass mInfo)
            : base(mInfo)
        {
            InitializeComponent();
            HandleSearch += new EventHandler(Cauta);
            HandleMoveFirst += new EventHandler(Primul);
            HandleMoveLast += new EventHandler(Ultimul);
            HandleMoveNext += new EventHandler(Urmator);
            HandleMovePrev += new EventHandler(Anterior);
            HandleAdd += new EventHandler(Adauga);
            HandleDel += new EventHandler(Sterge);
            HandleCard += new EventHandler(Card);
            
        }
        /// <summary>
        /// doar pentru designer
        /// </summary>
        protected FrmRezumat()
            : base(null)
        {
            InitializeComponent();
        }

        /// <summary>
        /// Functia apelata inainte de inchiderea machetei pentru verificarea
        /// existentei unor modificari nesalvate
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public virtual void FrmRezumat_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (listBndSourceMain.Count > 0)
            {
                currentRow = ((DataRowView)listBndSourceMain[0].Current);
            }
            DataTable _localDT = GetDataTable(0);
            if (ReadOnly || (_localDT==null))
            {
                return;
            }
            DataSet retData = _localDT.DataSet.GetChanges();
            String tabeleModificate = String.Empty;
            
            if ( retData!= null && retData.Tables.Count!=0)
            {
                foreach (DataTable dtab in retData.Tables)
                {
                    if (dtab.Rows.Count != 0)
                        tabeleModificate += dtab.TableName + ",";
                }
                MessageBoxFrm mbt = new MessageBoxFrm("Decideți", "Au fost modificate tabelele:" + tabeleModificate, "Renuntati la modificarile efectuate pana acum?", MessageBoxFrm.ImaginiMB.IntrebareIcon, retData);
                mbt.AddButton("Da", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.AddButton("Nu", 70, mbt.MessageBoxFrm_Click_No);
                DialogResult retD = mbt.ShowDialog();
                if (retD != DialogResult.Yes)
                {
                    e.Cancel = true;
                }
            }
        }

        private void FrmRezumat_Load(object sender, EventArgs e)
        {
            if (_selectionAddOn)
            { 
                //initializarile modului selectie din grid...
                AddButton("Selectie", global::ERPStudio.Properties.Resources.checkmark, Selectie, ToolStripItemAlignment.Right,false);
                //KeyPreview = false;
                SendKeys.Flush();
            }
        }

        public void InitializeBindingSource(String _DataMember,object _DataSource)
        {
            if ((listBndSourceMain.Count!=0) && (listBndSourceMain[0] != null))
            {
                listBndSourceMain[0].DataMember = _DataMember;
                listBndSourceMain[0].DataSource = _DataSource;
            }
        }

        private Boolean _bsExtern = false;

        public void InitializeBindingSource(BindingSource _bs)
        {
            if(_bs != null){
                if (listBndSourceMain.Count == 0)
                    listBndSourceMain.Add(_bs);
                else
                    listBndSourceMain[0] = _bs ;
                _bsExtern = true;
            }
        }

        public void InitializeBindingSource(BindingSource _bs, BindingSource _bsDetaliu)
        {
            if (_bs != null && _bsDetaliu!=null)
            {
                if (listBndSourceMain.Count <2)
                {
                    listBndSourceMain.Add(_bs);
                    listBndSourceMain.Add(_bsDetaliu);
                }
                else
                {
                    listBndSourceMain[0] = _bs;
                    listBndSourceMain[1] = _bsDetaliu;
                }
                _bsExtern = true;
            }
        }

        private void FrmRezumat_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_bsExtern && listBndSourceMain[0] != null)
                listBndSourceMain[0] = null;
        }

        virtual public void Cauta(object sender, EventArgs ev)
        {

            //in primul e masterul in al doile e details-ul
            //if (!SalvareLocal()) return;
            try
            {
                Trace.Assert(listBndSourceMain.Count > 0, "Nu s-a completata BindingSource!");
                Trace.Assert(gridRezumat.Count > 0, "Nu s-a setat gridul rezumat");

                Int16 indBGV = GetCurrentGrid();
                Trace.Assert(indBGV!=-1,"Atentie grid curent inexistent!!!");
                //acuta indexul de la BS
                int idxCurent = -1;
                foreach(BindingSource bs in listBndSourceMain)
                    if(((BindingSource)gridRezumat[indBGV].DataSource) == bs)
                    {
                        idxCurent = listBndSourceMain.IndexOf(bs);
                        break;
                    }
                Trace.Assert(idxCurent != -1,"Nu exista corespondenta intre grid si date");
                if (this.listBndSourceMain.Count > 0 && gridRezumat != null)
                {
                    FrmSearch frmS = null;
                    SqlConnection conn = DeschideConexiune(workConnString);
                    frmS = new FrmSearch(/*listDataTable[idxCurent],*/ listBndSourceMain[idxCurent],conn,ModuleInfo);
                    frmS.ShowDialog();
                    InchideConexiune(conn);
                }
                UpdateBounds();
                SetTitle();
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
            }
        }
    }
}